<?php
class Wx extends Lxbase{
	public $appid;
	public $secret;
	public $token;
	public $acctoken;
	public $shopid;
	public $shopkey;
	public $ticket;
	
	public function setwxinfo($userid=''){
		if(empty($userid)){$userid=$this->userinfo['userid'];}
		$view=$this->viewdata("*","wxuser","where userid={$userid}");
		if(empty($view)){
			echo "<script>alert('没有找到用户微信信息，请在商户设置中配置微信公众号信息')</script>";
			exit;
		}
		$this->appid = $view["appid"];
		$this->secret = $view["secret"];
		$this->token = $view["token"];
		if(time() > intval($view["acctokentim"]) || empty($view["acctoken"])){
			$tokeninfo = $this->get_access_token();
			if(empty($tokeninfo["access_token"])){
				die("<script>alert('获取accesstoken失败，请检查公众号配置')</script>");
			}
			$this->acctoken = $tokeninfo["access_token"];
			$acctokentim = time()+intval($tokeninfo["expires_in"])-200;
			$this->updata("wxuser","acctoken='{$this->acctoken}',acctokentim={$acctokentim}","where userid={$userid}");
		}else{
			$tempurl = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$view["acctoken"];
			$temret = json_decode($this->call_get($tempurl),true);
			if(!empty($temret["ip_list"])){
				$this->acctoken=$view["acctoken"];
			}else{
				$tokeninfo = $this->get_access_token();
				if(empty($tokeninfo["access_token"])){
				die("<script>alert('获取accesstoken失败，请检查公众号配置')</script>");
			}
				$this->acctoken = $tokeninfo["access_token"];
				$acctokentim = time()+intval($tokeninfo["expires_in"])-200;
				$this->updata("wxuser","acctoken='{$this->acctoken}',acctokentim={$acctokentim}","where userid={$userid}");
			}
		}
		if(time()>$view["tickettim"]){
			$ticket = $this->get_jsapi_ticket($this->acctoken);
			$this->ticket = $ticket;
			$tickettim=time()+3600;
			$this->updata("wxuser","ticket='{$ticket}',tickettim={$tickettim}","where userid={$userid}");
		}else{
			$this->ticket = $view["ticket"];
		}
		$this->shopid = $view["shopid"];
		$this->shopkey = $view["shopkey"];
	}
	
	//验证微信服务器
	public function checkwx(){
		$echoStr = $_GET["echostr"];
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$tmpArr = array($this->token,$timestamp,$nonce);
		sort($tmpArr);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
	//获取ACCESS_TOKEN
	public function get_access_token($appid='',$secret=''){
		if(empty($appid)){
			$appid = $this->appid;
		}
		if(empty($secret)){
			$secret = $this->secret;
		}
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$ret = json_decode($this->call_get($url),true);
		return $ret;
	}

	//刷新用户TOKEN
	public function get_rusertoken($rusertoken){
		$url='https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token='.$rusertoken;
		$ret = json_decode($this->call_get($url),true);
		return $ret;
	}
	
	
	
	//接收信息转数组
	public function xmltoarr($str){
		$temarr=simplexml_load_string($str,'SimpleXMLElement',LIBXML_NOCDATA);
		$data["tuid"]=$temarr->ToUserName;
		$data["fuid"]=$temarr->FromUserName;
		$data["tim"]=$temarr->CreateTime;
		$data["type"]=$temarr->MsgType;
		$data["id"]=$temarr->MsgId;
		if($data["type"]=='text'){
			$data["content"]=$temarr->Content;
		}elseif($data["type"]=='image'){
			$data["pic"]==$temarr->PicUrl;
			$data["media_id"]=$temarr->MsgId;
		}elseif($data["type"]=='voice'){
			$data["media_id"]=$temarr->MsgId;
			$data["format"] = $temarr->Format;
		}elseif($data["type"]=='video' || $data["type"]=='shortvideo'){
			$data["media_id"]=$temarr->MsgId;
			$data["pic"] = $temarr->ThumbMediaId;
		}elseif($data["type"]=='location'){
			$data["x"]=$temarr->Location_X;
			$data["y"]=$temarr->Location_Y;
			$data["size"]=$temarr->Scale;
			$data["content"]=$temarr->Label;
		}elseif($data["type"]=='link'){
			$data["title"]=$temarr->Title;
			$data["content"]=$temarr->Description;
			$data["url"]=$temarr->Url;
		}elseif($data["type"]=='event'){
			$data["event"]=$temarr->Event;
			$data["eventkey"]=$temarr->EventKey;
			if(!empty($temarr->Ticket)){
				$data["ticket"] = $temarr->Ticket;
			}
			if(!empty($temarr->Latitude)){
				$data["lat"]=$temarr->Latitude;
				$data["log"] = $temarr->Longitude;
				$data["pre"] = $temarr->Precision;
			}
			if(!empty($temarr->PoiId)){
				$data["Result"] = $temparr->Result;
				$data["Msg"] = $temparr->Msg;
				$data["UniqId"] = $temarr->UniqId;
				$data["PoiId"] = $temarr->PoiId;
			}
		}
		return $data;
	}
	
	//通用签名
	public function getsign($arr,$key)
		{
			//签名步骤一：按字典序排序参数
			ksort($arr);
			foreach($arr as $k=>$v){
				$str .= $k."=".$v."&";
			}		
			//签名步骤二：在string后加入KEY
			$str = trim($str,"&")."&key=".$key;
			//签名步骤三：MD5加密
			$str = md5($str);
			//签名步骤四：所有字符转为大写
			$result = strtoupper($str);
			return $result;
	}
	
	//统一支付
	public function weixin_pay($data){
	$str='<xml>
	   <appid>'.$data["appid"].'</appid>
	   <attach>'.$data["attach"].'</attach>
	   <body>'.$data["body"].'</body>
	   <mch_id>'.$data["mch_id"].'</mch_id>
	   <nonce_str>'.$data['nonce_str'].'</nonce_str>
	   <notify_url>'.$data["notify_url"].'</notify_url>
	   <openid>'.$data["openid"].'</openid>
	   <out_trade_no>'.$data["out_trade_no"].'</out_trade_no>
	   <spbill_create_ip>'.$data["spbill_create_ip"].'</spbill_create_ip>
	   <total_fee>'.$data["total_fee"].'</total_fee>
	   <trade_type>'.$data["trade_type"].'</trade_type>
	   <sign>'.$data["sign"].'</sign>
	</xml>';
	return $str;	
	}
	
	
	//微信自动回复
	public function wxrepost($data){
		$str='';
		if($data["type"]=='text'){
			$str='<xml><ToUserName>'.$data["tuid"].'</ToUserName><FromUserName>'.$data['fuid'].'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>text</MsgType><Content><![CDATA['.$data["content"].']]></Content></xml>';
		}elseif($data["type"]=='link'){
			$str='<xml><ToUserName>'.$data["fuid"].'</ToUserName><FromUserName>'.$data['tuid'].'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>link</MsgType><Title>'.$data["content"].'</Title><Description>'.$data["link"].'</Description><Url>'.$data["link"].'<Url></xml>';
		}elseif($data["type"]=='image'){
			$str='<xml><ToUserName>'.$data["tuid"].'</ToUserName><FromUserName>'.$data['fuid'].'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>image</MsgType><Image><MediaId>'.$data["media_id"].'</MediaId></Image></xml>';
		}elseif($data["type"]=='voice'){
			$str='<xml><ToUserName><![CDATA['.$data["tuid"].']]></ToUserName><FromUserName><![CDATA['.$data["fuid"].']]></FromUserName><CreateTime>'.time().'</CreateTime><MsgType>voice</MsgType><Voice><MediaId><![CDATA['.$data["media_id"].']]></MediaId></Voice></xml>';
		}elseif($data["type"]=='video'){
			$str='<xml><ToUserName><![CDATA['.$data["tuid"].']]></ToUserName><FromUserName><![CDATA['.$data["fuid"].']]></FromUserName><CreateTime>'.time().'</CreateTime><MsgType>video</MsgType><Video><MediaId><![CDATA['.$data["media_id"].']]></MediaId><Title><![CDATA['.$data["title"].']]></Title><Description><![CDATA['.$data["desc"].']]></Description></Video></xml>';
		}elseif($data["type"]=='news'){
			$news = $data["news"];
			$num=count($news);
			$str='<xml><ToUserName>'.$data["tuid"].'</ToUserName><FromUserName>'.$data['fuid'].'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>news</MsgType><ArticleCount>'.$num.'</ArticleCount><Articles>';
			foreach($news as $v){
				$str.='<item><Title>'.$v["title"].'</Title><Description><![CDATA['.strip_tags($v["digest"]).']]></Description><PicUrl><![CDATA['.$v["url"].']]></PicUrl><Url><![CDATA['.$v["content_source_url"].']]></Url></item>'; 
			 }
			$str.='</Articles></xml>';
		}else{
			$str='<xml><ToUserName>'.$data["tuid"].'</ToUserName><FromUserName>'.$data['fuid'].'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>'.$data['type'].'</MsgType></xml>';
		}
		return $str;
	}
	
	
	//回复文本
	public function repost_txt($data){
		$str='<xml>
	 <ToUserName>'.$data["tuid"].'</ToUserName>
	 <FromUserName>'.$data['fuid'].'</FromUserName>
	 <CreateTime>'.time().'</CreateTime>
	 <MsgType>text</MsgType>
	 <Content><![CDATA['.$data["content"].']]></Content>
	 </xml>';
	 return $str;
	}
	
	//回复语音
	public function repost_voice($data){
		$str='<xml>
		<ToUserName><![CDATA['.$data["tuid"].']]></ToUserName>
		<FromUserName><![CDATA['.$data["fuid"].']]></FromUserName>
		<CreateTime>'.time().'</CreateTime>
		<MsgType><![CDATA[voice]]></MsgType>
		<Voice>
		<MediaId><![CDATA['.$data["media_id"].']]></MediaId>
		</Voice>
		</xml>';	
	}
	
	//回复视频
	public function repost_video($data){
		$str='<xml>
		<ToUserName><![CDATA['.$data["tuid"].']]></ToUserName>
		<FromUserName><![CDATA['.$data["fuid"].']]></FromUserName>
		<CreateTime>'.time().'</CreateTime>
		<MsgType><![CDATA[video]]></MsgType>
		<Video>
		<MediaId><![CDATA['.$data["media_id"].']]></MediaId>
		<Title><![CDATA['.$data["title"].']]></Title>
		<Description><![CDATA['.$data["desc"].']]></Description>
		</Video> 
		</xml>';
	}
	
	//回复音乐
	public function repost_music($data){
		$str='<xml>
	 <ToUserName>'.$data["tuid"].'</ToUserName>
	 <FromUserName>'.$data["fuid"].'</FromUserName>
	 <CreateTime>'.time().'</CreateTime>
	 <MsgType>music</MsgType>
	 <Music>
	 <Title>'.$data["title"].'</Title>
	 <Description>'.$data["desc"].'</Description>
	 <MusicUrl>'.$data["murl"].'</MusicUrl>
	 <HQMusicUrl>'.$data["hdurl"].'</HQMusicUrl>
	 </Music>
	 </xml>';
	 return $str;
	}
	
	//回复图文
	public function repost_news($data){
		$news = $data["news"];
		$num=count($news);
		$str='<xml>
		 <ToUserName>'.$data["tuid"].'</ToUserName>
		 <FromUserName>'.$data['fuid'].'</FromUserName>
		 <CreateTime>'.time().'</CreateTime>
		 <MsgType>news</MsgType>
		 <ArticleCount>'.$num.'</ArticleCount>
		 <Articles>';
	 foreach($news as $k=>$v){
		$str.='<item><Title>'.$news[$k]["title"].'</Title><Description>'.$news[$k]["content"].'</Description><PicUrl>'.$news[$k]["url"].'</PicUrl><Url>'.$news[$k]["content_source_url"].'</Url></item>'; 
	 }
	 $str.='</Articles></xml>';
	 return $str;
	}
	
	//回复图片
	public function repost_img($data){
		$str='<xml>
	 <ToUserName>'.$data["tuid"].'</ToUserName>
	 <FromUserName>'.$data['fuid'].'</FromUserName>
	 <CreateTime>'.time().'</CreateTime>
	 <MsgType>image</MsgType>
	 <Image>
	 <Mediald>'.$data["media_id"].'</Mediald>
	 </Image>
	 </xml>';
	 return $str;
	}
	//回复客服消息
	public function repost_message($data){
		$this->setwxinfo();
		$url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->acctoken;
		$result = $this->call_post($url,json_encode($data));
		return $result;
	}
	//获取access_token
	public function get_access(){
		$this->setwxinfo();
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
		$info=json_decode($this->call_get($url),true);
		if(!empty($info["access_token"])){
			return $info;
		}else{
			return 'error';
		}
	}
	
	//获取微信素材图片链接
	public function getmediaurl($file){
		$this->setwxinfo();
		if(empty($file)){
			return array("errcode"=>1001,"errmsg"=>"file is NULL");
		}
		$data = array("media"=>"@".$file);
		$url ='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$this->acctoken;
		$ret = $this->call_post($url,$data);
		$rs = json_decode($ret,true);
		if(!empty($rs["url"])){
			return $rs["url"];
		}else{
			return $rs;
		}
		exit;
	}
	
	
	//新增临时素材 type类型包含 news image voice video thumb
	public function settempmedia($file,$type){
		$this->setwxinfo();
		if(empty($file) || empty($type)){
			return array("errcode"=>1001,"errmsg"=>"file or type is NULL");
		}
		$data = array("media"=>"@".$file);
		$url = 'http://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$this->acctoken.'&type='.$type;
		$ret = $this->call_post($url,$data);
		$rs = json_decode($ret,true);
		if(!empty($rs["media_id"])){
			return $rs["media_id"];
		}else{
			return $rs;
		}
		exit;
	}
	
	//新增永久素材 type类型包含 news image voice video thumb
	public function setmedia($file,$type="news"){
		$this->setwxinfo();
		if(empty($file) || empty($type)){
			return array("errcode"=>1001,"errmsg"=>"file or type is NULL");
		}
		if($type=='news'){
			$url = 'http://api.weixin.qq.com/cgi-bin/material/add_news?access_token='.$this->acctoken.'&type='.$type;
			$data = json_encode($file,JSON_UNESCAPED_UNICODE); 
		}elseif($type=='video'){
			$url ='https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$this->acctoken.'&type='.$type;
			$data["media"] = "@".$file["file"];
			$data["description"] = json_encode(array("title"=>$file["title"],"introduction"=>$file["desc"]),JSON_UNESCAPED_UNICODE );
		}else{
			$url ='https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$this->acctoken.'&type='.$type;
			$data["media"] = '@'.$file;
		}
		$ret = $this->call_post($url,$data);
		$rs = json_decode($ret,true);
		if(!empty($rs["media_id"])){
			return $rs["media_id"];
		}else{
			return $rs;
		}
	}
	
	
	
	//上传新闻素材
	public function setwxnews($arr){
		$this->setwxinfo();
		$data["articles"] = $arr;
		$url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$this->acctoken;
		$ret = $this->call_post($url,$data);
		$rs = json_decode($ret,true);
		if(!empty($rs["media_id"])){
			return $rs["media_id"];
		}else{
			return $rs;
		}
	}
	
	//修改图文素材
	public function updatenews($data){
		$this->setwxinfo();
		$url='https://api.weixin.qq.com/cgi-bin/material/update_news?access_token='.$this->acctoken;
		$ret = $this->call_post($url,json_encode($data,JSON_UNESCAPED_UNICODE));
		$rs = json_decode($ret,true);
		if(!empty($rs["errcode"])){
			return $rs;
		}else{
			return true;
		}
	}
	
	//获取永久素材
	public function getwxmedia($media_id){
		$this->setwxinfo();
		$url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$this->acctoken;
		$data["media_id"]=$media_id;
		$ret = $this->call_post($url,json_encode($data));
		return $ret;
	}
	
	//删除素材
	public function delwxmedia($media){
		$this->setwxinfo();
		$data["media_id"]=$media;
		$url='https://api.weixin.qq.com/cgi-bin/material/del_material?access_token='.$this->acctoken;
		$ret = $this->call_post($url,json_encode($data));
		$rs = json_decode($ret,true);
		if(empty($rs["errcode"])){
			return true;
		}else{
			return false;
		}
	}
	
	//群发消息 sel=群发的用户人群 $type=群发的内容类型 $content=群发的内容
	public function wxsendall($sel='',$type,$content){
		$this->setwxinfo();
		if(empty($sel)){
			$data["filter"]["is_to_all"]=true;
			$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$this->acctoken;
		}elseif(is_array($sel)){
			$data["touser"] = $sel;
			$url='https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$this->acctoken;
		}elseif(is_int($sel)){
			$data["filter"]["group_id"]=$sel;
			$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$this->acctoken;
		}
		if($type=='text'){
			$data["text"]["content"]=$content;
		}elseif($type=='mpnews'){
			$data["mpnews"]["media_id"]=$content;
		}elseif($type=='voice'){
			$data["voice"]["media_id"] = $content;
		}elseif($type=='image'){
			$data["image"]["media_id"] = $content;
		}elseif($type=='mpvideo'){
			$data["mpvideo"]["media_id"] = $content["media_id"];
			$data["mpvideo"]["title"] = $content["title"];
			$data["mpvideo"]["description"] = $content["desc"];
		}elseif($type=='wxcard'){
			$data["wxcard"]["card_id"]=$content;
		}
		$data["msgtype"]=$type;
		$ret = $this->call_post($url,json_encode($data,JSON_UNESCAPED_UNICODE));
		$rs = json_decode($ret,true);
		if(empty($rs["errcode"])){
			return true;
		}else{
			return false;
		}
		exit;
	}
	
	//获得前端JS票据
	public function get_jsapi_ticket($acctoken){
		$ret = $this->call_get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$acctoken}&type=jsapi");
		$ticketinfo = json_decode($ret,true);
		if(!empty($ticketinfo["ticket"])){
			return $ticketinfo["ticket"];
		}else{
			return '';
		}
	}
	
	//菜单名称转码
	public function menucode($array){
		if(!empty($array["button"])){
			$temp=$array["button"];
			foreach($temp as $k=>$v)
			{
				$temp[$k]["name"]=urlencode($temp[$k]["name"]);
				if(!empty($temp[$k]["sub_button"])){
					foreach($temp[$k]["sub_button"] as $kk=>$vv)
					{
						$temp[$k]["sub_button"][$kk]["name"]=urlencode($vv["name"]);
						if(!empty($vv["url"])){
							$temp[$k]["sub_button"][$kk]["url"]=urlencode($vv["url"]);
						}
					}
				}elseif(!empty($temp[$k]["url"])){
					$temp[$k]["url"]=urlencode($temp[$k]["url"]);
				}
			}
			$array["button"]=$temp;
			return urldecode(json_encode($array));
		}else{
			return '';
		}
	}
	
	//获得用户好友分组
	public function getwxgroup(){
		$bs_id=$_SESSION['userinfo']['userid'];
		$user_data=$this->viewdata("*","wxuser","where userid=$bs_id");
		if(time()>$user_data['acctokentim']){
			$this->setwxinfo($bs_id);
			$user_token=$this->acctoken;
		}else{
			$user_token=$user_data['acctoken'];
		}
		$url="https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$user_token";
		$ret = $this->call_get($url);
		$rs = json_decode($ret,true);
		if(!empty($rs["groups"])){
			return $rs["groups"];
		}else{
			return $rs;
		}
	}
	
	//创建微信菜单l
	public function menu_create($data){
		$this->setwxinfo();
		/*菜单创建演示
		$data=array(
			"button"=>array(
				0=>array("type"=>"click","name"=>'菜单测试1',"key"=>"V1001_TODAY_MUSIC"),
				1=>array("type"=>"view","name"=>'菜单测试2',"url"=>"http://lxcms.sinaapp.com/home.php"),
				2=>array("name"=>'菜单',"sub_button"=>array(
						0=>array("type"=>"click","name"=>"hello word","key"=>"V1001_HELLO_WORLD"),
						1=>array("type"=>"click","name"=>'赞我',"key"=>"V1001_GOOD")
						)
				)
			)
		);
		*/
		$wxdata["button"] = $data;
		$url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->acctoken;
		$info=json_decode($this->call_post($url,json_encode($wxdata,JSON_UNESCAPED_UNICODE)),true);
		if($info["errcode"]==0){
			return 1;
		}else{
			return $info;
		}
	}
	
	public function getfanslist($userid){
		$this->setwxinfo($userid);
		$url='https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$this->acctoken;
		$ret=json_decode($this->call_get($url),true);
		return $ret;
	}
	
	public function getfansinfo($acctoken,$openid){
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$acctoken}&openid={$openid}&lang=zh_CN";
		$ret = json_decode($this->call_get($url),true);
		return $ret;
	}
	 
	//菜单删除
	public function menu_del(){
		$this->setwxinfo();
		$url='https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->acctoken;
		$info=json_decode($this->call_get($url),true);
		if($info["errcode"]==0){
			return 1;
		}else{
			return 0;
		}
	}
	
	//微信JS签名
	function getjssign($arr){
		ksort($arr);
		foreach($arr as $k=>$v){
			$str .= $k."=".$v."&";
		}
		$str = sha1(trim($str,"&"));
		return $str;
	}
	
	//微信支付后台签名
	public function wxpaysign($arr,$key){
		ksort($arr);
		foreach($arr as $k=>$v){
			$str .= $k."=".$v."&";
		}
		$str = trim($str,"&")."&key=".$key;
		$str = md5($str);
		$result = strtoupper($str);
		$arr["sign"] = $result;
		return $arr;
	}
	
	//微信支付JSAPI签名
	public function wxpayjsapi($arr,$key){
		ksort($arr);
		foreach($arr as $k=>$v){
			$str .= $k."=".$v."&";
		}
		$str = trim($str,"&")."&key=".$key;
		$str = md5($str);
		$result = strtoupper($str);
		$arr["paySign"] = $result;
		return $arr;
	}
	
	public function checkSign($token='',$tim,$nonce){
		$token = empty($token)?'1nsya3on1hgdy5ryuy2lfmensibl1n13':$token;
		$signkey = array($token,$tim,$nonce);
		sort($signkey, SORT_STRING);
		$signString = implode($signkey);
		$signString = sha1($signString);
		return $signString;
	}
	
	
}